<template>
  <div class="profile-container" v-loading.fullscreen.lock="isPageLoading" element-loading-text="正在加载用户信息...">
    <!-- 顶部个人信息展示区 -->
    <div class="profile-header">
      <div class="profile-cover">
        <div class="cover-overlay"></div>
      </div>
      <div class="profile-info">
        <div class="avatar-wrapper">
          <el-avatar 
            :size="120" 
            :src="userInfo.photo || defaultAvatar"
            @error="handleAvatarError"
          />
          <!-- <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <div class="upload-mask">
              <el-icon><Camera /></el-icon>
              <span>更换头像</span>
            </div>
          </el-upload> -->
        </div>
        <div class="user-info">
          <h1 class="username">
            <template v-if="isEditingNickname">
              <el-input
                v-model="tempNickname"
                ref="nicknameInputRef"
                size="large"
                @blur="handleNicknameBlur"
                @keyup.enter="handleNicknameBlur"
              />
            </template>
            <template v-else>
              <span>{{ userInfo.name || '未设置昵称' }}</span>
              <!-- <el-icon 
                class="edit-icon" 
                @click="startEditNickname"
              >
                <Edit />
              </el-icon> -->
            </template>
          </h1>
          <p class="signature">{{ userInfo.signature || '这个人很懒，什么都没写~' }}</p>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="profile-content">
      <!-- 左侧导航 -->
      <div class="profile-nav">
        <div class="nav-item" 
          :class="{ active: currentTab === 'basic' }"
          @click="currentTab = 'basic'"
        >
          <el-icon><User /></el-icon>
          <span>基本资料</span>
        </div>
        <div class="nav-item"
          :class="{ active: currentTab === 'security' }"
          @click="currentTab = 'security'"
        >
          <el-icon><Lock /></el-icon>
          <span>账号安全</span>
        </div>
        <div class="nav-item"
          :class="{ active: currentTab === 'notification' }"
          @click="currentTab = 'notification'"
        >
          <el-icon><Bell /></el-icon>
          <span>消息通知</span>
        </div>
        <div class="nav-item"
          :class="{ active: currentTab === 'settings' }"
          @click="currentTab = 'settings'"
        >
          <el-icon><Setting /></el-icon>
          <span>账号设置</span>
        </div>
      </div>

      <!-- 右侧表单内容 -->
      <div class="profile-form-wrapper">
        <!-- 基本资料表单 -->
        <el-form
          v-if="currentTab === 'basic'"
          ref="formRef"
          :model="userInfo"
          :rules="rules"
          label-width="100px"
          class="profile-form"
        >
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            <el-form-item label="米米号" prop="account">
              <el-input v-model="userInfo.account" disabled />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userInfo.email" disabled />
            </el-form-item>
          </div>

          <div class="form-section game-info-section">
            <h3 class="section-title">
              <el-icon><Trophy /></el-icon>
              游戏信息
            </h3>
            
            <el-form-item label="昵称" prop="name">
              <el-input 
                v-model="userInfo.gameInfo.nick"
                placeholder="请输入游戏昵称"
                maxlength="12"
                show-word-limit
              />
            </el-form-item>

            <div class="game-stats">
              <div class="stat-item">
                <div class="stat-label">宠物总数</div>
                <div class="stat-value">{{ userInfo.gameInfo.petAllNum || '暂无数据' }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">宠物最大等级</div>
                <div class="stat-value">{{ userInfo.gameInfo.petMaxLev || '暂无数据' }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">怪物之王胜利次数</div>
                <div class="stat-value">{{ userInfo.gameInfo.monKingWin || '0' }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">勇者之塔当前阶段</div>
                <div class="stat-value">{{ userInfo.gameInfo.curStage || '0' }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">混战胜利次数</div>
                <div class="stat-value">{{ userInfo.gameInfo.messWin || '0' }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">竞技场最高连胜</div>
                <div class="stat-value">{{ userInfo.gameInfo.maxArenaWins || '0' }}</div>
              </div>
            </div>

            <div class="game-achievements">
              <h4 class="sub-title">
                <el-icon><Medal /></el-icon>
                SPT
              </h4>
              <div class="empty-achievement-container">
                <div class="stage-images-wrapper">
                  <div class="stage-images-scroll">
                    <div 
                      v-for="(image, index) in stageImages" 
                      :key="index"
                      class="stage-image-container"
                      :class="{ 'passed': image.pass }"
                    >
                      <img 
                        :src="image.path"
                        class="stage-image-content"
                        alt="stage image"
                        @error="handleStageImageError"
                      />
                    </div>
                  </div>
                </div>
                <div class="arrow-wrapper left" @click="changeImage('prev')" v-show="currentImageIndex > 0">
                  <el-icon class="arrow-icon"><ArrowLeft /></el-icon>
                </div>
                <div class="arrow-wrapper right" @click="changeImage('next')" v-show="currentImageIndex < stageImages.length - 1">
                  <el-icon class="arrow-icon"><ArrowRight /></el-icon>
                </div>
              </div>
            </div>
          </div>

          <!-- <div class="form-actions">
            <el-button type="primary" @click="handleSubmit" :loading="loading">
              保存修改
            </el-button>
            <el-button @click="resetForm">重置</el-button>
          </div> -->
        </el-form>

        <!-- 账号安全表单 -->
        <template v-if="currentTab === 'security'">
          <div class="form-section">
            <h3 class="section-title">修改密码</h3>
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="100px"
            >
              <el-form-item label="当前邮箱">
                <el-input v-model="userInfo.email" disabled />
              </el-form-item>
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input
                  v-model="passwordForm.oldPassword"
                  type="password"
                  show-password
                  placeholder="请输入旧密码"
                />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  show-password
                  placeholder="请输入新密码"
                />
              </el-form-item>
              <el-form-item label="令牌" prop="token">
                <div class="token-input-group">
                  <el-input
                    :value="displayPasswordToken"
                    @input="(val) => passwordForm.token = val"
                    placeholder="请输入令牌"
                    :prefix-icon="Lock"
                    readonly
                  />
                  <el-button 
                    type="primary" 
                    @click="getChangePasswordToken"
                    :disabled="!passwordForm.oldPassword || !passwordForm.newPassword"
                    :loading="passwordLoading"
                  >
                    获取修改令牌
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="handleChangePassword" 
                  :loading="passwordLoading"
                  :disabled="!passwordForm.token"
                >
                  修改密码
                </el-button>
              </el-form-item>
              <transition name="fade">
                <div v-if="passwordForm.token" class="qrcode-container">
                  <img :src="qrimage1" alt="修改密码二维码" class="register-qrcode" />
                  <p class="qrcode-tip">扫码进群，激活后才可以修改!</p>
                  <p class="qrcode-tip">入群的QQ需和邮箱为同一账号</p>
                  <p class="qrcode-tip">加群发送令牌即可完成激活</p>
                  <p class="qrcode-tip">再点击确认修改即可修改密码</p>
                </div>
              </transition>
            </el-form>
          </div>

          <!-- 修改邮箱区域 -->
          <div class="form-section" v-if="!isQQEmail">
            <h3 class="section-title">修改邮箱</h3>
            <el-form
              ref="emailFormRef"
              :model="emailForm"
              :rules="emailRules"
              label-width="100px"
            >
              <el-form-item label="当前邮箱">
                <el-input v-model="userInfo.email" disabled />
              </el-form-item>
              <el-form-item label="新邮箱" prop="newEmail">
                <el-input
                  v-model="emailForm.newEmail"
                  placeholder="请输入新邮箱地址"
                  type="email"
                />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="emailForm.password"
                  type="password"
                  show-password
                  placeholder="请输入当前密码"
                />
              </el-form-item>
              <el-form-item label="验证码" prop="captcha">
                <div class="captcha-input-group">
                  <el-input
                    v-model="emailForm.captcha"
                    placeholder="请输入邮箱验证码"
                    maxlength="6"
                  />
                  <el-button 
                    type="primary" 
                    @click="sendEmailCaptcha"
                    :disabled="!emailForm.newEmail || emailCaptchaCountdown > 0 || emailLoading"
                    :loading="emailCaptchaLoading"
                  >
                    {{ emailCaptchaCountdown > 0 ? `${emailCaptchaCountdown}s后重发` : '发送验证码' }}
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="handleChangeEmail" 
                  :loading="emailLoading"
                  :disabled="!emailForm.newEmail || !emailForm.captcha || !emailForm.password"
                >
                  修改邮箱
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 二级密码设置区域 -->
          <div class="form-section">
            <h3 class="section-title">二级密码设置</h3>
            <p class="section-desc">二级密码用于上架和购买物品时的安全验证，默认密码为111111，修改请扫描上方二维码修改二级密码</p>
            
            <!-- 开关 -->
            <el-form-item label="启用二级密码">
              <el-switch
                v-model="isSwitchEnabled"
                @change="handleSecondaryPasswordSwitch"
                inline-prompt
                active-text="开"
                inactive-text="关"
                :loading="loading"
              />
            </el-form-item>

            <!-- 仅当开关开启时显示密码输入和按钮 -->
            <el-form
              v-if="isSwitchEnabled"
              ref="secondaryPasswordFormRef"
              :model="secondaryPasswordForm"
              :rules="secondaryPasswordRules"
              label-width="100px"
            >
              <el-form-item label="二级密码" prop="secondaryPassword">
                <el-input
                  v-model="secondaryPasswordForm.secondaryPassword"
                  type="password"
                  show-password
                  placeholder="请输入6位数字二级密码"
                  maxlength="6"
                  :disabled="!isSwitchEnabled"
                />
              </el-form-item>
              <el-form-item label="令牌" prop="token">
                <div class="token-input-group">
                  <el-input
                    :value="displaySecondaryPasswordToken"
                    @input="(val) => secondaryPasswordForm.token = val"
                    placeholder="请输入令牌"
                    :prefix-icon="Lock"
                    :disabled="!isSwitchEnabled"
                    readonly
                  />
                  <el-button 
                    type="primary" 
                    @click="getSecondaryPasswordToken"
                    :disabled="!isSwitchEnabled || !secondaryPasswordForm.secondaryPassword || secondaryPasswordForm.secondaryPassword === '●●●●●●'"
                    :loading="secondaryPasswordLoading"
                  >
                    获取设置令牌
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="handleSetSecondaryPassword" 
                  :loading="secondaryPasswordLoading"
                  :disabled="!isSwitchEnabled || !secondaryPasswordForm.token"
                >
                  {{ userInfo.hasSecondaryPassword === 1 ? '修改二级密码' : '设置二级密码' }}
                </el-button>
              </el-form-item>
              <transition name="fade">
                <div v-if="isSwitchEnabled && secondaryPasswordForm.token" class="qrcode-container">
                  <img :src="qrimage1" alt="二级密码设置二维码" class="register-qrcode" />
                  <p class="qrcode-tip">扫码进群，激活后才可以设置!</p>
                  <p class="qrcode-tip">入群的QQ需和邮箱为同一账号</p>
                  <p class="qrcode-tip">加群发送令牌即可完成激活</p>
                  <p class="qrcode-tip">再点击确认设置即可设置二级密码</p>
                </div>
              </transition>
            </el-form>
          </div>
        </template>
      </div>
    </div>

    <!-- 新增：关闭二级密码验证对话框 -->
    <el-dialog 
      v-model="verifyDisableDialogVisible" 
      title="验证二级密码"
      width="400px"
      append-to-body
      :close-on-click-modal="false"
    >
      <p>请输入您的二级密码以确认关闭该功能。</p>
      <el-form :model="verifyDisableForm" @submit.prevent="confirmDisableVerification">
        <el-form-item prop="password">
          <el-input
            v-model="verifyDisableForm.password"
            type="password"
            show-password
            placeholder="请输入6位数字二级密码"
            maxlength="6"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="verifyDisableDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmDisableVerification" 
            :loading="verificationLoading"
          >
            确认关闭
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed, watch } from 'vue'
import { ElMessage, ElSwitch, ElDialog, ElInput, ElForm, ElFormItem, ElButton } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { updatePassword, sendCaptcha, setSecondaryPassword, verifySecondaryPassword, switchSecondPassword, addSecondPassword, generateRegisterToken, updateEmail } from '@/api/user'
import { useSystemStore } from '@/stores/index'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { User, Lock, Bell, Setting, Edit, Medal, Camera, Warning } from '@element-plus/icons-vue'

const defaultAvatar = 'https://robohash.org/10.png'
const qrimage1 = ref('http://seerxin.com/go/check/image')
const systemStore = useSystemStore()
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

// General Form Refs & Loadings
const formRef = ref(null)
const loading = ref(false)
const isPageLoading = ref(false)

// Password Change Form
const passwordFormRef = ref(null)
const passwordLoading = ref(false)
const passwordForm = reactive({ newPassword: '', email: '', oldPassword: '', token: '' })

// Email Change Form
const emailFormRef = ref(null)
const emailLoading = ref(false)
const emailCaptchaLoading = ref(false)
const emailCaptchaCountdown = ref(0)
const emailForm = reactive({ newEmail: '', captcha: '', password: '' })

// 计算属性：显示密码修改令牌的前4位，其余用*代替
const displayPasswordToken = computed(() => {
  if (!passwordForm.token) return '';
  return passwordForm.token.substring(0, 4);
});

// 计算属性：判断是否为QQ邮箱
const isQQEmail = computed(() => {
  if (!userInfo.value || !userInfo.value.email) return false;
  return userInfo.value.email.toLowerCase().endsWith('@qq.com');
});
const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  token: [
    { required: true, message: '请输入令牌', trigger: 'blur' }
  ]
}

// Email Change Rules
const emailRules = {
  newEmail: [
    { required: true, message: '请输入新邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === userInfo.value.email) {
          callback(new Error('新邮箱不能与当前邮箱相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' }
  ]
}

// Secondary Password Area
const secondaryPasswordFormRef = ref(null)      // Ref for the form element
const secondaryPasswordLoading = ref(false)    // Loading for set/modify button
const secondaryPasswordForm = reactive({ secondaryPassword: '', token: '' }) // Form model for input

// 计算属性：显示二级密码令牌的前4位，其余用*代替
const displaySecondaryPasswordToken = computed(() => {
  if (!secondaryPasswordForm.token) return '';
  return secondaryPasswordForm.token.substring(0, 4);
});
const secondaryPasswordRules = { 
  secondaryPassword: [],
  token: [
    { required: true, message: '请输入令牌', trigger: 'blur' }
  ]
} // Validation rules
const isSwitchEnabled = computed(() => userStore.userInfo.isSecondaryPasswordActive === 1) // Computed switch state

// Secondary Password Disable Verification Dialog
const verifyDisableDialogVisible = ref(false)
const verifyDisableForm = reactive({ password: '' })
const verificationLoading = ref(false)       // Loading for dialog confirmation button

// Nickname Editing
const isEditingNickname = ref(false)
const tempNickname = ref('')
const nicknameInputRef = ref(null)

// Other state
const currentTab = ref('basic')
const stageImages = ref([ /* ... stage images ... */ ])
const currentImageIndex = ref(0)
console.log(userInfo.value.isSecondaryPasswordActive);

onMounted(async () => {
  if (!userStore.userInfo.account) {
    isPageLoading.value = true
    try {
      await userStore.fetchUserInfo()
      console.log(userStore.userInfo.isSecondaryPasswordActive);
    } catch (error) {
      ElMessage.error('获取用户信息失败')
      console.error('获取用户信息失败:', error)
    } finally {
      isPageLoading.value = false
    }
  }
  // Initialize secondary password form display
  if (userInfo.value.hasSecondaryPassword === 1 && userInfo.value.isSecondaryPasswordActive === 1) {
    secondaryPasswordForm.secondaryPassword = '●●●●●●'
  } else if (userInfo.value.hasSecondaryPassword === 1 && userInfo.value.isSecondaryPasswordActive === 0) {
    // If exists but inactive, maybe still show placeholder?
    secondaryPasswordForm.secondaryPassword = '●●●●●●' // Or clear: ''
  }
})

// ... other functions (changeImage, beforeAvatarUpload, handleAvatarUpload, handleAvatarError, handleSubmit, resetForm, sendPasswordCode, handleChangePassword, handleNicknameBlur, updateStageStatus, refreshUserInfo, handleStageImageError) ...

// 获取修改密码令牌
const getChangePasswordToken = async () => {
  if (!passwordForm.oldPassword || !passwordForm.newPassword) {
    ElMessage.warning('请先填写旧密码和新密码')
    return
  }
  
  try {
    passwordLoading.value = true
    const res = await generateRegisterToken({
      email: userInfo.value.email,
      password: passwordForm.newPassword
    })
    
    if (res.code === 200) {
      passwordForm.token = res.token
      ElMessage.success('令牌获取成功，请扫码加入QQ群激活令牌')
    } else {
      ElMessage.error(res.msg || '令牌获取失败')
    }
  } catch (error) {
    console.error('获取修改密码令牌失败:', error)
    ElMessage.error('令牌获取失败')
  } finally {
    passwordLoading.value = false
  }
}

// 处理修改密码
const handleChangePassword = async () => {
  if (!passwordForm.token) {
    ElMessage.warning('请先获取并激活令牌')
    return
  }

  try {
    passwordLoading.value = true
    let res = await updatePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      email: userInfo.value.email,
      token: passwordForm.token
    })
    
    if (res.code === 200) {
      ElMessage.success('密码修改成功')
      // 重置表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.token = ''
    } else {
      ElMessage.error(res.msg || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('密码修改失败')
  } finally {
    passwordLoading.value = false
  }
}

// 发送邮箱验证码
const sendEmailCaptcha = async () => {
  // 验证新邮箱格式
  try {
    await emailFormRef.value.validateField('newEmail')
  } catch (error) {
    return
  }

  try {
    emailCaptchaLoading.value = true
    // 立即开始倒计时
    startEmailCaptchaCountdown()
    
    const res = await sendCaptcha({
      email: userInfo.value.email,
      scene: 'update'
    })
    
    if (res.code === 200) {
      ElMessage.success('验证码发送成功，请查收邮箱')
    } else {
      ElMessage.error(res.msg || '验证码发送失败')
      // API失败时重置倒计时
      emailCaptchaCountdown.value = 0
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('验证码发送失败')
    // 请求异常时重置倒计时
    emailCaptchaCountdown.value = 0
  } finally {
    emailCaptchaLoading.value = false
  }
}

// 邮箱验证码倒计时
const startEmailCaptchaCountdown = () => {
  emailCaptchaCountdown.value = 60
  const timer = setInterval(() => {
    emailCaptchaCountdown.value--
    if (emailCaptchaCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 处理修改邮箱
const handleChangeEmail = async () => {
  if (!emailFormRef.value) return
  
  try {
    await emailFormRef.value.validate()
  } catch (error) {
    return
  }

  try {
    emailLoading.value = true
    const res = await updateEmail({
      email: userInfo.value.email,
      newEmail: emailForm.newEmail,
      password: emailForm.password, // Ensure this line is present
      captcha: emailForm.captcha
    })
    
    if (res.code === 200) {
      ElMessage.success('邮箱修改成功')
      // 重置表单
      emailForm.newEmail = ''
      emailForm.captcha = ''
      emailForm.password = '' // Reset password field
      // 刷新用户信息
      await userStore.fetchUserInfo()
    } else {
      ElMessage.error(res.msg || '邮箱修改失败')
    }
  } catch (error) {
    console.error('修改邮箱失败:', error)
    ElMessage.error('邮箱修改失败')
  } finally {
    emailLoading.value = false
  }
}

// 获取二级密码令牌
const getSecondaryPasswordToken = async () => {
  if (!secondaryPasswordForm.secondaryPassword || secondaryPasswordForm.secondaryPassword === '●●●●●●') {
    ElMessage.warning('请先输入6位数字二级密码')
    return
  }
  
  if (!/^\d{6}$/.test(secondaryPasswordForm.secondaryPassword)) {
    ElMessage.error('二级密码必须是6位数字')
    return
  }
  
  try {
    secondaryPasswordLoading.value = true
    const res = await generateRegisterToken({
      email: userInfo.value.email,
      password: secondaryPasswordForm.secondaryPassword,
      type: 'secondary'
    })
    
    if (res.code === 200) {
      secondaryPasswordForm.token = res.token
      ElMessage.success('令牌获取成功，请扫码加入QQ群激活令牌')
    } else {
      ElMessage.error(res.msg || '令牌获取失败')
    }
  } catch (error) {
    console.error('获取二级密码令牌失败:', error)
    ElMessage.error('令牌获取失败')
  } finally {
    secondaryPasswordLoading.value = false
  }
}

// 设置/修改二级密码
const handleSetSecondaryPassword = async () => {
  if (secondaryPasswordForm.secondaryPassword === '●●●●●●') {
     ElMessage.warning('请输入新的6位数字二级密码');
     secondaryPasswordForm.secondaryPassword = ''; // Clear placeholder on error
     return;
  }
  
  if (!/^\d{6}$/.test(secondaryPasswordForm.secondaryPassword)) {
    ElMessage.error('二级密码必须是6位数字')
    return
  }
  
  if (!secondaryPasswordForm.token) {
    ElMessage.warning('请先获取并激活令牌')
    return
  }

  secondaryPasswordLoading.value = true
  try {
    const res = await setSecondaryPassword({ 
      password: secondaryPasswordForm.secondaryPassword,
      token: secondaryPasswordForm.token
    })
    
    if (res.code === 200) {
      ElMessage.success(userInfo.value.hasSecondaryPassword === 1 ? '二级密码修改成功' : '二级密码设置成功')
      await userStore.fetchUserInfo() 
      // Update form display based on new state
      if (userInfo.value.hasSecondaryPassword === 1 && userInfo.value.isSecondaryPasswordActive === 1) {
        secondaryPasswordForm.secondaryPassword = '●●●●●●'
      } else {
        secondaryPasswordForm.secondaryPassword = '' 
      }
      // 重置令牌
      secondaryPasswordForm.token = ''
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('设置/修改二级密码失败:', error)
    ElMessage.error('操作失败')
  } finally {
    secondaryPasswordLoading.value = false
  }
}

// Handling the Enable/Disable Switch
const handleSecondaryPasswordSwitch = async (enabled) => { // `enabled` is boolean from switch
  loading.value = true;
  if (!enabled) {
    // Trying to disable: Open verification dialog
    verifyDisableForm.password = '';
    verifyDisableDialogVisible.value = true;
    // Don't change switch state here, v-model handles it if dialog is cancelled/fails
  } else {
    // Trying to enable
    let apiCall;
    if (userInfo.value.hasSecondaryPassword === 0) {
      apiCall = addSecondPassword();
    } else {
      apiCall = switchSecondPassword({ status: 1 });
    }
    try {
      const res = await apiCall; 
      if (res.code === 200) {
        ElMessage.success(`二级密码已开启`);
        await userStore.fetchUserInfo(); // Refresh store, computed property updates switch
        secondaryPasswordForm.secondaryPassword = '●●●●●●';
      } else {
        ElMessage.error(res.msg || '开启失败');
        // Switch state reverts automatically via v-model if API fails
      }
    } catch (error) {
      console.error('开启二级密码状态失败:', error);
      ElMessage.error('操作失败');
      // Switch state reverts automatically via v-model if error occurs
    }finally{
      loading.value = false;
    }
  }
};

// Confirming the Disable Action via Dialog
const confirmDisableVerification = async () => {
  if (!/^\d{6}$/.test(verifyDisableForm.password)) {
    ElMessage.error('二级密码必须是6位数字');
    return;
  }
  verificationLoading.value = true;
  try {
    const res = await switchSecondPassword({ 
      password: verifyDisableForm.password, 
      status: 0 
    });
    if (res.code === 200) {
      ElMessage.success('二级密码已关闭');
      verifyDisableDialogVisible.value = false; 
      await userStore.fetchUserInfo(); // Refresh store, computed property updates switch
    } else {
      ElMessage.error(res.msg || '关闭失败'); // Keep dialog open on failure
    }
  } catch (error) {
    console.error('关闭二级密码操作失败:', error);
    ElMessage.error('操作失败，请重试');
  } finally {
    verificationLoading.value = false;
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.profile-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  transition: background-color 0.3s ease;

  // 顶部个人信息展示区
  .profile-header {
    position: relative;
    height: 360px;
    background: #fff;
    margin-bottom: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    
    .profile-cover {
      height: 240px;
      background: linear-gradient(135deg, #6b8afd, #4466f2);
      position: relative;
      overflow: hidden;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('');
        background-repeat: repeat;
        opacity: 0.1;
        animation: backgroundMove 30s linear infinite;
      }

      .cover-overlay {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 120px;
        background: linear-gradient(to bottom, transparent, rgba(0,0,0,0.4));
        backdrop-filter: blur(2px);
      }
    }

    .profile-info {
      position: absolute;
      left: 50%;
      bottom: 40px;
      transform: translateX(-50%);
      display: flex;
      align-items: flex-end;
      gap: 32px;
      z-index: 1;
      
      .avatar-wrapper {
        position: relative;
        width: 160px;
        height: 160px;
        border-radius: 50%;
        border: 6px solid #fff;
        box-shadow: 0 8px 32px rgba(0,0,0,0.15);
        overflow: hidden;
        transform: translateY(0);
        transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
        
        &:hover {
          transform: translateY(-8px);
          box-shadow: 0 12px 40px rgba(0,0,0,0.2);
        }
        
        .el-avatar {
          width: 100%;
          height: 100%;
          transition: transform 0.6s ease;

          &:hover {
            transform: scale(1.1);
          }
        }

        .upload-mask {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0,0,0,0.6);
          backdrop-filter: blur(2px);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #fff;
          opacity: 0;
          transform: translateY(10px);
          transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
          cursor: pointer;

          .el-icon {
            font-size: 28px;
            margin-bottom: 8px;
            transform: translateY(10px);
            transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
          }

          span {
            transform: translateY(10px);
            transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1) 0.1s;
          }

          &:hover {
            opacity: 1;
            transform: translateY(0);

            .el-icon, span {
              transform: translateY(0);
            }
          }
        }
      }

      .user-info {
        color: #fff;
        text-shadow: 0 2px 8px rgba(0,0,0,0.3);
        min-width: 300px;

        .username {
          font-size: 36px;
          font-weight: 700;
          margin: 0 0 12px;
          letter-spacing: 0.5px;
          position: relative;
          display: inline-flex;
          align-items: center;
          gap: 12px;
          text-shadow: 2px 2px 8px rgba(0,0,0,0.4);

          .el-input {
            width: 300px;
            
            :deep(.el-input__wrapper) {
              background: rgba(0,0,0,0.2);
              box-shadow: none;
              padding: 0 8px;
              border-radius: 4px;
              
              .el-input__inner {
                height: 44px;
                color: #fff;
                font-size: 36px;
                font-weight: 700;
                padding: 0;
                text-shadow: 2px 2px 8px rgba(0,0,0,0.4);
                
                &::placeholder {
                  color: rgba(255,255,255,0.9);
                }
              }
            }
          }

          .edit-icon {
            font-size: 22px;
            cursor: pointer;
            opacity: 0;
            transition: all 0.3s ease;
            color: rgba(255,255,255,0.9);
            background: rgba(0,0,0,0.2);
            padding: 6px;
            border-radius: 50%;
            
            &:hover {
              color: #fff;
              transform: scale(1.1);
              background: rgba(0,0,0,0.3);
            }
          }

          &:hover {
            .edit-icon {
              opacity: 1;
            }
          }
        }

        .signature {
          font-size: 16px;
          opacity: 1;
          max-width: 400px;
          line-height: 1.6;
          position: relative;
          margin-top: 16px;
          text-shadow: 2px 2px 6px rgba(0,0,0,0.4);
          background: linear-gradient(135deg, rgba(0,0,0,0.4), rgba(0,0,0,0.3));
          padding: 12px 24px;
          border-radius: 12px;
          border-left: 6px solid rgba(255,255,255,0.6);
          backdrop-filter: blur(8px);
          transform: translateY(0);
          transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
          box-shadow: 0 4px 16px rgba(0,0,0,0.2);
          margin-bottom: 12px;

          &:hover {
            transform: translateY(-4px) translateX(2px);
            background: linear-gradient(135deg, rgba(0,0,0,0.5), rgba(0,0,0,0.4));
            border-left-color: rgba(255,255,255,0.9);
            box-shadow: 0 8px 24px rgba(0,0,0,0.3);
          }

          &::before {
            content: '"';
            position: absolute;
            left: 12px;
            top: 4px;
            font-size: 32px;
            font-family: "Georgia", serif;
            opacity: 0.9;
            color: rgba(255,255,255,0.8);
            text-shadow: 2px 2px 8px rgba(0,0,0,0.6);
          }

          &::after {
            content: '"';
            position: absolute;
            right: 12px;
            bottom: -6px;
            font-size: 32px;
            font-family: "Georgia", serif;
            opacity: 0.9;
            color: rgba(255,255,255,0.8);
            text-shadow: 2px 2px 8px rgba(0,0,0,0.6);
          }
        }
      }
    }
  }

  // 内容区域
  .profile-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 24px;
    display: flex;
    gap: 24px;

    // 左侧导航
    .profile-nav {
      width: 240px;
      background: #fff;
      border-radius: 16px;
      padding: 20px;
      height: fit-content;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
      transform: translateY(0);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
      }

      .nav-item {
        display: flex;
        align-items: center;
        padding: 16px;
        margin: 4px 0;
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
        position: relative;
        overflow: visible;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: var(--el-color-primary);
          opacity: 0;
          transform: translateX(-100%);
          transition: all 0.3s ease;
        }

        .el-icon {
          font-size: 20px;
          margin-right: 12px;
          color: #666;
          position: relative;
          z-index: 1;
          transition: all 0.3s ease;
        }

        span {
          font-size: 15px;
          color: #333;
          position: relative;
          z-index: 1;
          transition: all 0.3s ease;
        }

        &:hover {
          transform: translateX(4px);
          
          &::before {
            opacity: 0.1;
            transform: translateX(0);
          }

          .el-icon, span {
            color: var(--el-color-primary);
          }
        }

        &.active {
          background: var(--el-color-primary);
          transform: translateX(4px);
          
          .el-icon, span {
            color: #fff;
          }

          &:hover {
            opacity: 0.95;
          }
        }
      }
    }

    // 右侧表单
    .profile-form-wrapper {
      flex: 1;
      background: #fff;
      border-radius: 16px;
      padding: 32px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
      transform: translateY(0);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
      }

      .form-section {
        margin-bottom: 40px;
        animation: fadeInUp 0.6s ease both;

        @for $i from 1 through 3 {
          &:nth-child(#{$i}) {
            animation-delay: #{$i * 0.1}s;
          }
        }

        .section-title {
          font-size: 18px;
          font-weight: 600;
          color: #1a1a1a;
          margin: 0 0 24px;
          padding-bottom: 16px;
          border-bottom: 1px solid #f0f2f5;
          position: relative;

          &::after {
            content: '';
            position: absolute;
            left: 0;
            bottom: -1px;
            width: 50px;
            height: 2px;
            background: var(--el-color-primary);
            transform: scaleX(0);
            transform-origin: left;
            transition: transform 0.3s ease;
          }

          &:hover::after {
            transform: scaleX(1);
          }
        }
      }

      .el-form-item {
        margin-bottom: 24px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateX(4px);
        }

        :deep(.el-form-item__label) {
          font-weight: 500;
          color: #1a1a1a;
          transition: color 0.3s ease;
        }

        :deep(.el-input__wrapper) {
          box-shadow: 0 2px 8px rgba(0,0,0,0.04);
          transition: all 0.3s ease;
          border-radius: 8px;
          display: flex;
          align-items: center;

          &:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
          }

          &.is-focus {
            box-shadow: 0 4px 16px rgba(var(--el-color-primary-rgb), 0.15);
          }
        }

        :deep(.el-input-group__append) {
          padding: 0;
          background: var(--el-input-bg-color, #fff);
          border: 1px solid var(--el-border-color);
          border-left: 1px solid var(--el-border-color);
          margin-left: -1px;
          border-top-right-radius: 8px;
          border-bottom-right-radius: 8px;
          
          .el-button {
            height: 40px;
            min-width: 100px;
            padding: 0 20px;
            border: none;
            border-radius: 8px;
            transition: all 0.3s ease;
            margin: 0;
            
            &:hover {
              transform: translateX(2px);
            }
            
            &:disabled {
              background-color: var(--el-button-disabled-bg-color);
              border-color: var(--el-button-disabled-border-color);
            }
          }
        }

        :deep(.el-input__inner) {
          transition: all 0.3s ease;
          
          &:focus {
            transform: translateX(4px);
          }
        }

        :deep(.el-radio-group) {
          .el-radio {
            margin-right: 24px;
            padding: 8px 16px;
            border-radius: 8px;
            transition: all 0.3s ease;

            &:hover {
              background: var(--el-color-primary-light-9);
              transform: translateY(-2px);
            }
          }
        }
      }

      .form-actions {
        margin-top: 40px;
        padding-top: 24px;
        border-top: 1px solid #f0f2f5;
        display: flex;
        justify-content: flex-end;
        gap: 16px;

        .el-button {
          padding: 12px 32px;
          font-size: 15px;
          border-radius: 8px;
          transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);

          &:hover {
            transform: translateY(-4px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
          }

          &:active {
            transform: translateY(-2px);
          }
        }
      }
    }
  }
}

// 动画关键帧
@keyframes backgroundMove {
  from {
    background-position: 0 0;
  }
  to {
    background-position: 100% 100%;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式布局优化
@media screen and (max-width: 1024px) {
  .profile-container {
    .profile-content {
      flex-direction: column;

      .profile-nav {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        padding: 16px;

        .nav-item {
          flex: 1;
          min-width: 160px;
          justify-content: center;
          padding: 12px;

          &:hover {
            transform: translateY(-4px);
          }
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .profile-container {
    .profile-header {
      height: auto;
      padding-bottom: 24px;

      .profile-cover {
        height: 180px;
      }

      .profile-info {
        position: relative;
        flex-direction: column;
        align-items: center;
        text-align: center;
        padding: 0 20px;
        margin-top: -80px;
        bottom: 0;

        .avatar-wrapper {
          width: 120px;
          height: 120px;
        }

        .user-info {
          color: #333;
          text-shadow: none;

          .signature {
            margin: 0 auto;
          }
        }
      }
    }

    .profile-content {
      padding: 0 16px;

      .profile-form-wrapper {
        padding: 20px;

        .el-form-item {
          &:hover {
            transform: none;
          }
        }
      }
    }
  }
}

.game-info-section {
  .game-stats {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-top: 20px;
    padding: 16px;
    background: var(--el-fill-color-light);
    border-radius: 8px;

    .stat-item {
      text-align: center;
      padding: 16px;
      background: var(--el-bg-color);
      border-radius: 8px;
      transition: all 0.3s ease;
      border: 1px solid var(--el-border-color-light);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
        border-color: var(--el-color-primary-light-5);
      }

      .stat-label {
        color: var(--el-text-color-secondary);
        font-size: 14px;
        margin-bottom: 8px;
      }

      .stat-value {
        color: var(--el-text-color-primary);
        font-size: 18px;
        font-weight: 600;
      }
    }
  }

  .game-achievements {
    margin-top: 24px;

    .sub-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      gap: 8px;

      .el-icon {
        color: var(--el-color-primary);
      }
    }

    .empty-achievement-container {
      position: relative;
      width: 100%;
      height: 180px;
      background: #f5f7fa;
      border-radius: 8px;
      border: 2px dashed #dcdfe6;
      display: flex;
      align-items: center;
      overflow: hidden;
      transition: all 0.3s;

      // 添加悬浮时显示箭头的效果
      &:hover {
        .arrow-wrapper {
          opacity: 1;
        }
      }

      .arrow-wrapper {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        width: 32px;
        height: 32px;
        background: rgba(255, 255, 255, 0.8);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        z-index: 2;
        opacity: 0;
        transition: all 0.3s ease;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

        &:hover {
          background: #fff;
          transform: translateY(-50%) scale(1.1);
        }

        &.left {
          left: 10px;
        }

        &.right {
          right: 10px;
        }
      }

      .stage-images-wrapper {
        display: flex;
        align-items: center;
        width: calc(100% - 80px);
        height: 100%;
        position: relative;
        overflow: hidden;
        margin: 0 40px;
      }

      .stage-images-scroll {
        display: flex;
        align-items: center;
        gap: 20px;
        position: relative;
        transition: transform 0.3s ease;
        transform: translateX(var(--scroll-offset, 0px));
        width: 100%;

        .stage-image-container {
          position: relative;
          flex: 0 0 calc((100% - 80px) / 5);
          display: flex;
          align-items: center;
          justify-content: center;
          height: 120px;
          
          .stage-image-content {
            max-width: 100%;
            max-height: 100%;
            width: auto;
            height: auto;
            object-fit: contain;
            display: block;
            transition: all 0.3s ease;
            filter: grayscale(100%);
            opacity: 0.6;
            transform: scale(0.85);
          }

          // 当pass为true时的样式
          &.passed {
            .stage-image-content {
              filter: grayscale(0%);
              opacity: 1;
              transform: scale(0.95);
            }
          }
        }
      }
    }
  }
}

/* 令牌输入组件样式 */
.token-input-group,
.captcha-input-group {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  
  .el-input {
    flex: 1;
  }
  
  .el-button {
    flex-shrink: 0;
    white-space: nowrap;
  }
}

/* 二维码容器样式 */
.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0px 0 0px;
  padding: 10px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

/* 二维码图片样式 */
.register-qrcode {
  width: 180px;
  height: 180px;
  object-fit: contain;
  border-radius: 4px;
  margin-bottom: 8px;
}

/* 二维码提示文字样式 */
.qrcode-tip {
  font-size: 14px;
  color: #94a3b8;
  text-align: center;
  margin: 0;
  margin-bottom: 12px;
}

@media screen and (max-width: 768px) {
  .game-info-section {
    .game-stats {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}
</style>